import { ref, onMounted } from 'vue'
import { useCache } from './useCache'

export function useDataFetching(fetchFunction, options = {}) {
  const {
    cacheKey,
    cacheDuration = 5 * 60 * 1000, // 默认5分钟缓存
    immediate = true,
    transform
  } = options

  const data = ref(null)
  const loading = ref(false)
  const error = ref(null)
  const { getCache, setCache } = useCache()

  const fetch = async (params) => {
    try {
      loading.value = true
      error.value = null

      // 检查缓存
      if (cacheKey) {
        const cached = getCache(cacheKey)
        if (cached) {
          data.value = cached
          return cached
        }
      }

      const response = await fetchFunction(params)
      const result = transform ? transform(response.data) : response.data
      
      data.value = result
      if (cacheKey) {
        setCache(cacheKey, result, cacheDuration)
      }
      
      return result
    } catch (err) {
      error.value = err
      throw err
    } finally {
      loading.value = false
    }
  }

  if (immediate) {
    onMounted(fetch)
  }

  return {
    data,
    loading,
    error,
    fetch
  }
} 